import json

from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.utils import timezone

from .models import Todo


def result(data=None, code=200, message="success", kwargs=None):
    json_dict = {'code': code, 'data': data, 'message': message}
    if kwargs and isinstance(kwargs, dict) and kwargs.keys():
        json_dict.update(kwargs)
    return JsonResponse(json_dict)


# Create your views here.
def getAllTodos(request):
    if request.method == "GET":
        todos = Todo.objects.all().values()
        todo_list = list(todos)
        for todo in todo_list:
            todo['create_time'] = timezone.localtime(todo['create_time']).strftime("%Y-%m-%d %H:%M:%S")
            todo['finish_time'] = timezone.localtime(todo['finish_time']).strftime("%Y-%m-%d %H:%M:%S")
        todo_list.reverse()
        return result(todo_list)


def handleTodo(request):
    if request.method == "POST":
        todo_title = json.loads(request.body).get('title')
        todo = Todo.objects.create(todo_title=todo_title)
        todo = model_to_dict(todo)
        return result(todo)
    elif request.method == "PUT":
        body = json.loads(request.body)
        check_status = body.get('checkStatus')
        todo_id = body.get('todoId')
        todo = Todo.objects.get(id=todo_id)
        todo.is_finished = check_status
        if check_status:
            todo.finish_time = timezone.now()
        else:
            todo.finish_time = None
        todo.save()
        todo = model_to_dict(todo)
        return result(todo)
    elif request.method == "GET":
        return result("GET")
    return result("Test")
